<template>
  <div class="main">
    <div class="mainContainer">

      <el-header style="position: absolute; width: 60%; height: 50px">Header</el-header>
      <div style="height: 50px"></div>
      <div class="picLable">
          <span v-for="(item, index) in links">
    <el-image
        style="width: 100px; height: 100px; margin: 2px"
        :src="item['url']"
        :zoom-rate="1.2"
        :max-scale="7"
        :min-scale="0.2"
        :preview-src-list="pics"
        :initial-index="index"
        fit="cover"
    />
  </span>
      </div>
    </div>
    <div class="input">
      <div class="input_inner">
        <el-form-item>
          <el-form>

            <el-upload
                class="avatar-uploader"
                action="#"
                :show-file-list="false"
                :before-upload="beforeAvatarUpload"
                :http-request="executeUpload"
            >
              <img v-if="imageUrl" :src="imageUrl" class="avatar"/>
              <el-icon v-else class="avatar-uploader-icon">
                <Plus/>
              </el-icon>
            </el-upload>
          </el-form>
          <div>
            <el-tree-select
                placeholder="加盐"
                v-model="value1"
                :data="data"
                multiple
                :render-after-expand="false"
                show-checkbox
                style="width: 240px; margin: 10px;"
            />
          </div>
        </el-form-item>
        <el-form
            ref="formRef"
            :model="prompts"
            label-width="auto"
            class="demo-ruleForm"
        >

          <el-form-item>
            <div v-for="(item, index) in prompts">
              <el-input
                  v-model="item['english']"
                  type="textarea"
                  autocomplete="off"
                  placeholder="English Prompt"
                  @input="debouncedTranslate(index, 'english')"
              />
              <el-input
                  v-model="item['chinese']"
                  type="textarea"
                  autocomplete="off"
                  placeholder="Chinese Prompt"
                  @input="debouncedTranslate(index, 'chinese')"
              />
              <div class="slider-demo-block">
                <span class="demonstration">Default value</span>
                <el-slider v-model="item.num"/>
              </div>
            </div>

          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm(formRef)">Submit</el-button>
            <el-button @click="resetForm(formRef)">Reset</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import {onMounted, onUnmounted, reactive, ref} from 'vue'
import type {FormInstance, UploadProps} from 'element-plus'
import {ElMessage} from 'element-plus'
import {Plus} from '@element-plus/icons-vue'
import axiosInstance from "@/utils/axios";
import {MD5} from "@/utils/MD5"
import {jsonp} from "vue-jsonp";
import {debounce} from 'lodash';
import {useStore} from 'vuex'; // 引入 Vuex store

const formRef = ref<FormInstance>()

const imageUrl = ref('')
const value1 = ref()
let prompts = ref([
  {
    'english': '',
    'chinese': '',
    'num': 0
  },
  {
    'english': '',
    'chinese': '',
    'num': 0
  },
  {
    'english': '',
    'chinese': '',
    'num': 0
  },
  {
    'english': '',
    'chinese': '',
    'num': 0
  }])
const data = [
  {
    value: '1',
    label: 'Level one 1',
    children: [
      {
        value: '1-1',
        label: 'Level two 1-1',
        children: [
          {
            value: '1-1-1',
            label: 'Level three 1-1-1',
          },
        ],
      },
    ],
  },
  {
    value: '2',
    label: 'Level one 2',
    children: [
      {
        value: '2-1',
        label: 'Level two 2-1',
        children: [
          {
            value: '2-1-1',
            label: 'Level three 2-1-1',
          },
          {
            value: '2-1-1',
            label: 'Level three 2-1-1',
          },
          {
            value: '2-1-1',
            label: 'Level three 2-1-1',
          },
          {
            value: '2-1-1',
            label: 'Level three 2-1-1',
          },
        ],
      },
      {
        value: '2-2',
        label: 'Level two 2-2',
        children: [
          {
            value: '2-2-1',
            label: 'Level three 2-2-1',
          },
        ],
      },
    ],
  },
  {
    value: '3',
    label: 'Level one 3',
    children: [
      {
        value: '3-1',
        label: 'Level two 3-1',
        children: [
          {
            value: '3-1-1',
            label: 'Level three 3-1-1',
          },
        ],
      },
      {
        value: '3-2',
        label: 'Level two 3-2',
        children: [
          {
            value: '3-2-1',
            label: 'Level three 3-2-1',
          },
        ],
      },
    ],
  },
]

const store = useStore();
const links = ref([
  {
    'url': 'http://gips0.baidu.com/it/u=3602773692,1512483864&fm=3028&app=3028&f=JPEG&fmt=auto?w=960&h=1280',
    'index': 0
  },
  {
    'url': 'http://gips0.baidu.com/it/u=3602773692,1512483864&fm=3028&app=3028&f=JPEG&fmt=auto?w=960&h=1280',
    'index': 1
  },
  {
    'url': 'http://gips0.baidu.com/it/u=3602773692,1512483864&fm=3028&app=3028&f=JPEG&fmt=auto?w=960&h=1280',
    'index': 2
  }
]);

const pics = ref(links.value.map(item => item.url));

let intervalId = null;

const fetchTaskList = async () => {
  try {
    let ids = [...store.state.imageCode.new]
    await axiosInstance.post('task/list-by-condition', {
      'ids': ids
    }).then(response => {
      for (let i = 0; i < response.data.length; i++) {
        let scopeParam = response.data[i];
        if (scopeParam.status === 'SUCCESS') {
          let index = store.state.imageCode.new.indexOf(scopeParam.id);
          if (index !== -1) {
            store.commit('appendImageCode', {
              new: [],
              old: [scopeParam.id]
            });
            store.commit('removeImageCode', {
              new: [scopeParam.id],
              old: []
            });
          }
          console.log(store.state.imageCode)
        }
      }
    }).catch(error => {
      console.error('error submit!', error);
    });
  } catch (error) {
    console.error('Error fetching task list:', error);
  }
};

onMounted(() => {
  if (store.state.imageCode.new.length > 0) {
    intervalId = setInterval(fetchTaskList, 2000);
  }
});


onUnmounted(() => {
  if (intervalId) {
    clearInterval(intervalId);
  }
});

async function submitDescribe(payload) {
  try {
    const response = await axiosInstance.post('/submit/describe', payload);
    console.log('upload!', response.data['result']);
    let respStatus = "";

    async function checkTaskStatus() {
      try {
        const taskResponse = await axiosInstance.post('/task/list-by-condition', {'ids': [response.data['result']]});
        console.log('task list!', taskResponse.data);

        if (taskResponse.data[0].prompt === "Unknown error") {
          alert('上传失败')
        } else if (taskResponse.data[0].status === 'SUCCESS') {
          imageUrl.value = taskResponse.data[0]['imageUrl']
          let promptData = taskResponse.data[0]['prompt']
              .replaceAll("1️⃣ ", '')
              .replaceAll("2️⃣ ", '')
              .replaceAll("3️⃣ ", '')
              .replaceAll("4️⃣ ", '')
              .split('\n\n')
          prompts.value = promptData.map((element, index) => {
            return {
              "english": element,
              "chinese": "",
              "num": 0
            }
          })
          prompts.value.forEach((prompt, index) => {
            callBaiduAPI(prompt.english, index, 'chinese', 'english');
          });
          respStatus = 'SUCCESS';
        } else if (taskResponse.data[0].status === "FAILURE") {
          alert('上传失败')
        } else {
          setTimeout(checkTaskStatus, 2000);
        }
      } catch (error) {
        console.error('task list error!', error.response || error.message);
      }
    }

    checkTaskStatus();

  } catch (error) {
    console.error('error upload!', error.response || error.message);
  }
}

const executeUpload = (file) => {
  console.log('file', file)
  var reader = new FileReader();
  reader.readAsDataURL(file.file);
  reader.onload = () => {
    console.log("file 转 base64结果：" + reader.result);
    const payload = {
      "base64": reader.result
    };

    console.log('payload', payload)

    submitDescribe(payload)
  };
}
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') { // 修改条件判断
    ElMessage.error('Avatar picture must be JPG or PNG format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 10) {
    ElMessage.error('Avatar picture size can not exceed 10MB!')
    return false
  }
  return true
}

const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      for (let obj of prompts.value) {
        if (obj.english === '' || obj.num < 1) {
          continue
        }
        const sendRequest = (index: number) => {
          if (index >= obj.num) return;
          const json_data = {
            'base64Array': [],
            'notifyHook': '',
            'prompt': obj.english,
            'state': '',
          }
          axiosInstance.post('/submit/imagine', json_data)
              .then(response => {
                console.log('submit!', response.data);
                // 将返回值放入 new 数组
                if (response.data.result !== null) {
                  store.commit('appendImageCode', {new: [response.data.result], old: []});

                }
                setTimeout(() => sendRequest(index + 1), 3000);
              })
              .catch(error => {
                console.error('error submit!', error);
                setTimeout(() => sendRequest(index + 1), 3000);
              });
        };
        sendRequest(0);
      }
    } else {
      console.log('error submit!')
    }
  })
}
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
const debouncedTranslate = debounce((index, field) => {
  const text = field === 'english' ? prompts.value[index].english : prompts.value[index].chinese;
  if (text === '') {
    return;
  }
  callBaiduAPI(text, index, field === 'english' ? 'chinese' : 'english', field);
}, 2000);
const callBaiduAPI = (text, index, targetField) => {
  var appid = '20240828002135064';
  var key = 'RmzDASXXXEc4bTFy7dOX';
  var salt = (new Date).getTime();
  var query = text;
  var from = targetField === 'chinese' ? 'en' : 'zh';
  var to = targetField === 'chinese' ? 'zh' : 'en';
  console.log(from + '_' + to)

  var str1 = appid + query + salt + key;
  var sign = MD5(str1);
  jsonp('http://api.fanyi.baidu.com/api/trans/vip/translate', {
    q: query,
    appid: appid,
    salt: salt,
    from: from,
    to: to,
    sign: sign
  }).then(response => {
    console.log(response)
    prompts.value[index][targetField] = response['trans_result'][0]['dst'];
  });
}

</script>

<style scoped>
.main {
  display: flex;
  height: 100vh;
}

.input {
  width: 600px;
  background-color: #989898;
  height: 100vh;
  overflow-y: auto;
}

.input_inner {
  padding: 20px;
}

.mainContainer {
  width: 100%;
  background-color: #fdc4c4;
  overflow-y: auto;
  height: 100%;
}

.avatar-uploader .avatar {
  width: 100px;
  height: 100px;
  display: block;
}
</style>


<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
}

.demonstration {
  width: 200px;
}

.slider-demo-block {
  max-width: 600px;
  display: flex;
  align-items: center;
}

.slider-demo-block .el-slider {
  margin-top: 0;
}

.slider-demo-block .demonstration {
  font-size: 14px;
  color: var(--el-text-color-secondary);
  line-height: 20px;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  margin-bottom: 0;
}

.slider-demo-block .demonstration + .el-slider {
  flex: 0 0 95%;
}

.picLable {
  margin: 20px;
}

.demo-image__error .image-slot {
  font-size: 30px;
}

.demo-image__error .image-slot .el-icon {
  font-size: 30px;
}

.demo-image__error .el-image {
  width: 100%;
  height: 200px;
}
</style>